import React, { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "../../store/store";
import { addTodo, deleteTodo, Todo, toggleTodo } from "../../store/todoSlice";
import { Link } from "react-router-dom";

const TodoHome: React.FC = () => {
    const [inputValue, setInputValue] = useState('');
    const todos = useSelector((state: RootState) => state.todos.items);
    const dispatch = useDispatch();

    const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        if (inputValue.trim()) {
          dispatch(addTodo(inputValue));
          setInputValue('');
        }
      };
      
    return (
        <div className="container mx-auto p-4 max-w-md">
            <Link to={'/money'} >To Money Page</Link>
        <h1 className="text-2xl font-bold mb-4">Todo List</h1>
        <form onSubmit={handleSubmit} className="mb-4">
          <input
            type="text"
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            placeholder="Add new todo"
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
          <button
            type="submit"
            className="mt-2 w-full bg-blue-500 text-white py-2 px-4 rounded-md hover:bg-blue-600 transition-colors"
          >
            Add
          </button>
        </form>
        <ul className="space-y-2">
          {todos.map((todo: Todo) => (
            <li
              key={todo.id}
              className={`flex items-center p-3 border rounded-md ${
                todo.completed ? 'bg-gray-100 line-through' : 'bg-white'
              }`}
            >
              <input
                type="checkbox"
                checked={todo.completed}
                onChange={() => dispatch(toggleTodo(todo.id))}
                className="mr-3"
              />
              <span>{todo.text}</span>
              <button
                onClick={() => dispatch(deleteTodo(todo.id))}
                className="ml-auto text-red-500 hover:text-red-700"
              >
                <i className="fas fa-trash"></i>
              </button>
            </li>
          ))}
        </ul>
      </div>
    );
};

export default TodoHome;